﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Security;
using System.Text;
using System.Xml;
using System.Xml.XPath;

namespace FeedsLibrary.Feeds.Abstract
{
    public abstract class AbstractItem : IItem
    {
        protected DateTime _lastBuildDate;

        public abstract void FeedSpecificAttributes(IXPathNavigable nodeItem);

        protected static DateTime GetDate(string date)
        {
            int i = 0;

            string strDiff = date.Substring(date.LastIndexOf(" ", StringComparison.InvariantCulture) + 1);

            if (date.EndsWith("GMT"))
            {
                //string s = "";
                date = date.Substring(0, date.LastIndexOf(" ", StringComparison.InvariantCulture));
            }
            else if (date.EndsWith("PST") || date.EndsWith("PDT"))
            {
                //string s = "";
                date = date.Substring(0, date.LastIndexOf(" ", StringComparison.InvariantCulture));
                i = 8;
            }
            else if (date.EndsWith("BST"))
            {
                //string s = "";
                date = date.Substring(0, date.LastIndexOf(" ", StringComparison.InvariantCulture));
                i = 1;
            }
            else if (date.EndsWith("EST") || date.EndsWith("EDT"))
            {
                //string s = "";
                date = date.Substring(0, date.LastIndexOf(" ", StringComparison.InvariantCulture));
                i = 5;
            }
            else
            {
                if (Int32.TryParse(strDiff, out i))
                {
                    strDiff = strDiff.Substring(0, strDiff.Length - 2);
                    i = Int32.Parse(strDiff);
                    if (i < 0)
                    {
                        i = i + (i*-2);
                    }
                    else
                    {
                        i = i - (i*2);
                    }
                }
            }

            DateTime result;
            try
            {
                result = DateTime.Parse(date);
                result = result.AddHours(i);
            }
            catch (Exception)
            {
                result = DateTime.Now;
            }

            return result;
        }

        protected void LoadStandardAttributes(string domain, IXPathNavigable nodeItem2)
        {
            Source = domain;
            XmlNode nodeItem = nodeItem2 as XmlNode;

            if (nodeItem["title"] != null)
            {
                Title = RemoveFormattingCharacters(nodeItem["title"].InnerText);
            }
            if (nodeItem["link"] != null)
            {
                Link = RemoveFormattingCharacters(nodeItem["link"].InnerText);
            }
            if (nodeItem["content"] != null)
            {
                Description = RemoveFormattingCharacters(nodeItem["content"].InnerText);
            }
            if (nodeItem["description"] != null)
            {
                Description = RemoveFormattingCharacters(nodeItem["description"].InnerText);
            }
            if (nodeItem["guid"] != null)
            {
                Guid = RemoveFormattingCharacters(nodeItem["guid"].InnerText);
            }
            if (nodeItem["source"] != null)
            {
                Source = RemoveFormattingCharacters(nodeItem["source"].InnerText);
            }
        }

        public string Save()
        {
            StringBuilder sb = new StringBuilder();
            //start item
            sb.Append("<item>\r\n");

            //standard bits
            sb.Append("<title>" + SecurityElement.Escape(Title) + "</title>\r\n");
            sb.Append("<link>" + SecurityElement.Escape(Link) + "</link>\r\n");
            sb.Append("<pubDate>" + SecurityElement.Escape(PubDate.ToUniversalTime().ToString("r")) + "</pubDate>\r\n");
            sb.Append("<guid>" + SecurityElement.Escape(Guid) + "</guid>\r\n");

            //custom bits
            sb.Append("<prizereader:iconurl>" + SecurityElement.Escape(IconUrl.AbsoluteUri) + "</prizereader:iconurl>\r\n");
            sb.Append("<prizereader:shortdate>" +
                      SecurityElement.Escape(String.Format("{0:t}", PubDate) + " " +
                                             String.Format("{0:d}", PubDate)) +
                      "</prizereader:shortdate>\r\n");

            //sort out the tags if present
            StringBuilder joinedTags = new StringBuilder();
            if (Tags != null)
            {
                Tags.Sort();
                string[] tags = Tags.ToArray();
                joinedTags.Append(SecurityElement.Escape(string.Join("|", tags)));
            }
            sb.Append("<prizereader:tags>" + joinedTags + "</prizereader:tags>\r\n");

            //end item
            sb.Append("</item>\r\n");

            return sb.ToString();
        }

        public int CompareTo(object obj)
        {
            if (obj is AbstractItem)
            {
                AbstractItem otherTemperature = (AbstractItem)obj;
                return PubDate.CompareTo(otherTemperature.PubDate);
            }
            throw new ArgumentException("Object is not a Temperature");
        }

        public bool Contains(string target)
        {
            string lcv = target.ToLower();
            bool found = false;

            if (Title != null)
            {
                found = Title.ToLower().Contains(lcv);
            }
            if (Description != null)
            {
                found = found || Description.ToLower().Contains(lcv);
            }

            return (found);
        }

        private static string RemoveFormattingCharacters(string s)
        {
            string result = s;

            //new line, etc
            result = result.Replace("\r", "");
            result = result.Replace("\n", "");
            result = result.Replace("\f", "");
            result = result.Replace("\t", "");
            result = result.Replace("<i>", "");

            //stray HTML
            result = result.Replace("</i>", "");

            return result;
        }

        #region properties

        public DateTime PubDate { get; set; }

        public string Title { get; set; }

        public string Description { get; set; }

        public string Guid { get; set; }

        public string Source { get; set; }

        public Uri IconUrl { get; set; }

        public string Link { get; set; }

        public bool Tagged { get; set; }

        public List<string> Tags { get; set; }

        public Image Icon { get; set; }

        #endregion properties
    }
}